package com.ruoyi.aitsms.service;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.service.IAitEntityInfoService;
import com.ruoyi.aitcommon.utils.EntityCache;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.RestServiceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信发送服务
 * 成都凌凯通信
 * 官网:http://www.028lk.com/
 * 管理端网址:https://cloud.028lk.com/
 */
@Service
public class LKSMSService {
    @Autowired
    EntityCache entityCache;
    @Autowired
    IAitEntityInfoService infoService;
    /**
     * 发送短信
     * @return
     */
    public void SendSMS(List<Map<String,Object>> datas,Map<String,Object> props,Map<String, Object> entityInfo) throws Exception {
        final Object url = props.get("url");
        ExceptionUtils.checkBlankOrUndefined(url,"SMS配置[url]为空");
        // 从缓存过滤重复数据
        List<Map<String, Object>> filterlist = entityCache.filterEntityChange(entityInfo, datas);
        for (Map<String, Object> data : filterlist) {
            try{
                final JSONObject retJson = restInvoke(props, url, data);
                infoService.insertAitEntityInfo(entityInfo, data, null);
            }catch (Exception ex){
                infoService.insertAitEntityInfo(entityInfo, data, ex);
            }
        }
    }

    /**
     * 短信发送
     * @param props 短信配置参数
     * @param url 短信接口url
     * @param data 短信发送数据
     * @throws Exception
     */
    private static JSONObject restInvoke(Map<String, Object> props, Object url, Map<String, Object> data) throws Exception {
//        获取配置数据
        final Object data1 = props.get("data");
        ExceptionUtils.checkBlankOrUndefined(data1,"SMS配置[data]为空");
        Map<String,Object> data2=(Map<String,Object>)data1;
//            合并配置数据+SQL数据
//            putall执行浅拷贝,如果value是字符串会进行拷贝,如果value是对象,指向的是相同对象
        data2.putAll(data);
//            调用接口
        JSONObject sendJson=new JSONObject(data2);
        final JSONObject retJson = RestServiceUtils.post(url.toString(), sendJson);
//            处理返回
        final Integer retCode = retJson.getInteger("code");
        if(retCode!=0){
            ExceptionUtils.throwException(null,"发送短信失败,错误消息:{}",retJson.getString("msg"));
        }
        return retJson;
    }
}
